package com.zp.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.RemoteClinicItemDictService;
import com.zp.base.api.vo.ClinicItemDictVo;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.system.api.RemoteBaseDictDataService;
import com.zp.system.api.bo.SysOrgDictBo;
import com.zp.system.api.entity.SysBaseDictData;
import com.zp.system.api.entity.SysOrgDict;
import com.zp.system.api.vo.SysOrgDictVo;
import com.zp.system.mapper.SysOrgDictMapper;
import com.zp.system.service.ISysOrgDictService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 机构数据字典Service业务层处理
 *
 * @author zhang peng
 * @ date 2024-03-08
 */
@RequiredArgsConstructor
@Service
public class SysOrgDictServiceImpl implements ISysOrgDictService {

    private final SysOrgDictMapper baseMapper;

    @DubboReference
    private RemoteClinicItemDictService clinicItemDictService;

    @DubboReference
    private RemoteBaseDictDataService remoteBaseDictDataService;

    /**
     * 查询机构数据字典
     */
    @Override
    public SysOrgDictVo queryById(String orgDictId) {
        return baseMapper.selectVoById(orgDictId);
    }

    /**
     * 查询机构数据字典列表(分页)
     */
    @Override
    public TableDataInfo<SysOrgDictVo> queryPageList(SysOrgDictBo bo, PageQuery pageQuery) {
        List<ClinicItemDictVo> clinicItemDictList = clinicItemDictService.getClinicItemDictList(bo.getClinicItemId());

        LambdaQueryWrapper<SysOrgDict> lqw = buildQueryWrapper(bo);
        Page<SysOrgDictVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(sysOrgDict -> {
            List<ClinicItemDictVo> collect = clinicItemDictList.stream().filter(item -> StringUtils.equals(sysOrgDict.getClinicItemId(), item.getClinicItemId())).collect((Collectors.toList()));
            if (CollectionUtil.isNotEmpty(collect)) {
                sysOrgDict.setItemName(collect.get(0).getItemName());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询机构数据字典列表(不分页)
     */
    @Override
    public List<SysOrgDictVo> queryList(SysOrgDictBo bo) {
        LambdaQueryWrapper<SysOrgDict> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysOrgDict> buildQueryWrapper(SysOrgDictBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOrgDict> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysOrgDict::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgDictId()), SysOrgDict::getOrgDictId, bo.getOrgDictId());
        lqw.eq(StringUtils.isNotBlank(bo.getLabel()), SysOrgDict::getLabel, bo.getLabel());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), SysOrgDict::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getValue()), SysOrgDict::getValue, bo.getValue());
        lqw.eq(bo.getSort() != null, SysOrgDict::getSort, bo.getSort());
        lqw.eq(StringUtils.isNotBlank(bo.getOutpOrInp()), SysOrgDict::getOutpOrInp, bo.getOutpOrInp());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), SysOrgDict::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增机构数据字典
     */
    @Override
    public Boolean insertByBo(SysOrgDictBo bo) {
        SysOrgDict add = BeanUtil.toBean(bo, SysOrgDict.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setOrgDictId(add.getOrgDictId());
        }
        return flag;
    }

    /**
     * 修改机构数据字典
     */
    @Override
    public Boolean updateByBo(SysOrgDictBo bo) {
        SysOrgDict update = BeanUtil.toBean(bo, SysOrgDict.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOrgDict entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除机构数据字典
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean saveBatchOrgDictInData(SysOrgDictBo bo) {
        List<SysOrgDict> sysOrgDictList = new ArrayList<SysOrgDict>();
        // 根据字典id查询存在的字典
        List<SysBaseDictData> baseDictDataList = remoteBaseDictDataService.selectExistBaseData(bo.getCheckList());
        if (CollectionUtil.isNotEmpty(baseDictDataList)) {
            baseDictDataList.forEach(item -> {
                SysOrgDict sysOrgDict = new SysOrgDict();
                BeanUtil.copyProperties(item, sysOrgDict);
                sysOrgDict.setOrgId(bo.getOrgId());
                sysOrgDictList.add(sysOrgDict);
            });
            baseMapper.insertBatch(sysOrgDictList);
        }
        return true;
    }

    @Override
    public boolean updateSysOrgDictToClinic(SysOrgDictBo bo) {
        LambdaUpdateWrapper<SysOrgDict> sysOrgDictLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        sysOrgDictLambdaUpdateWrapper.set(SysOrgDict::getClinicItemId, bo.getClinicItemId());
        sysOrgDictLambdaUpdateWrapper.eq(SysOrgDict::getOrgDictId, bo.getOrgDictId());
        return baseMapper.update(null, sysOrgDictLambdaUpdateWrapper) > 0;
    }

    @Override
    public SysOrgDictVo getDictPrices(SysOrgDictBo bo) {
        SysOrgDictVo sysOrgDictVo = new SysOrgDictVo();
        List<SysOrgDictVo> sysOrgDictVoList = this.queryList(bo);
        if (CollectionUtil.isNotEmpty(sysOrgDictVoList)) {
            // 获取选中字典信息
            sysOrgDictVo = sysOrgDictVoList.get(0);
            List<String> clinicItemIdArray = new ArrayList<>();
            clinicItemIdArray.add(sysOrgDictVo.getClinicItemId());
            Map<String, Object> map = new HashMap<>();
            map.put("clinicItemDictVo", clinicItemDictService.getClinicItemsAndPriceList(sysOrgDictVo.getOrgId(), null, clinicItemIdArray));
            sysOrgDictVo.setClinicItemDictMap(map);
            return sysOrgDictVo;
        }
        return null;
    }
}
